package com.jie.other.jetpack.paging.inhttp

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.blankj.utilcode.util.LogUtils
import com.jie.other.jetpack.paging.bean.Repo
import com.net.okhttphelper.http.ExceptionHandle

/**
 * 直接请求网络数据，当页面监听到数据发生改变时，自动刷新列表
 * 参考资料：
 * https://github.com/Tommys-code/Jetpack-samples
 * https://github.com/android/architecture-components-samples/tree/main/PagingWithNetworkSample
 */
class HttpPagingSource(private val dataService: GithubService) : PagingSource<Int, Repo>() {

    companion object {
        const val QUERY_KEY = "Android"
        const val FIRST_PAGE_NUM = 1
        const val NETWORK_PAGE_SIZE = 10
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val pageNum = params.key?: FIRST_PAGE_NUM
            val pageSize = params.loadSize
            val body = dataService.searchRepos(QUERY_KEY, pageNum, pageSize)
            if (pageNum >= 30) {
                // 模拟加载完成
                return LoadResult.Page(
                    data = emptyList(),
                    prevKey = null,
                    nextKey = null
                )
            }
            LoadResult.Page(
                data = body.items,
                prevKey = null,
                nextKey = if (body.items.isEmpty()) {
                    null
                } else {
                    // 由于第一次加载会默认加载 3 * pageSize，故需要做如下处理
                    params.loadSize / NETWORK_PAGE_SIZE + pageNum
                }
            )
        } catch (e : Exception) {
            LogUtils.i("数据来源出错：${e}")
            LoadResult.Error(Throwable(ExceptionHandle.handlerException(e)))
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey
        }
    }

}